﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.Linq;
using System.Configuration;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;

namespace notifier
{
    class notifier
    {
        
        //name of command topic
        private const string CQNAME = "cqueue";
        //name of status topic
        private const string RQNAME = "outqueue";
        //name of service bus
        private const string SBNAME = "<service bus namespace>";
        //service bus key
        private const string SBKEY = "<service bus key>";
        //service bus owner
        private const string SBISSUER = "owner";
       

        //Connection Strings
        private const string _sbconnectionstring = "Endpoint=sb://<service bus namespace>.servicebus.windows.net;SharedSecretIssuer=owner;SharedSecretValue=<service bus key>";

        static void Main(string[] args)
        {
            //connect to results topic
          //  TopicClient rqclient = TopicClient.CreateFromConnectionString(_sbconnectionstring, RQNAME);
           // TopicClient cqclient = TopicClient.CreateFromConnectionString(_sbconnectionstring, CQNAME);
            var sbnamespace = NamespaceManager.CreateFromConnectionString(_sbconnectionstring);
            //sbnamespace.CreateSubscription(CQNAME, "CommandMonitor");
           if (!sbnamespace.SubscriptionExists(RQNAME, "ResultMonitor"))
                sbnamespace.CreateSubscription(RQNAME, "ResultMonitor");
            //subscribe to commands and filter by jobid actually owned
           // SubscriptionClient subclient1 = SubscriptionClient.CreateFromConnectionString(_sbconnectionstring, CQNAME, "CommandMonitor");
            SubscriptionClient subclient2 = SubscriptionClient.CreateFromConnectionString(_sbconnectionstring, RQNAME, "ResultMonitor");

            char keypressed = 'n';
            Console.WriteLine("Press q to quit.");
            

                subclient2.OnMessage((msg) =>
                    {
                        Console.WriteLine("Message id: {0}, JobID: {1} Content: {2}", msg.MessageId, msg.Properties["JobID"],msg.GetBody<string>());
                        msg.Complete();
                       
                    });
                while (keypressed != 'q')
                {
                    keypressed = Convert.ToChar(Console.Read());
                }

            subclient2.Close();
            sbnamespace.DeleteSubscription(RQNAME, "ResultMonitor");
        }
    }
}
